package com.swa99ylum.pjv.sample.s04_others.s0400;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.swa99ylum.pjv.Fuse;
import com.swa99ylum.pjv.PluggableJSONValidator;
import com.swa99ylum.pjv.bean.ArrayJSONNode;
import com.swa99ylum.pjv.bean.JSONNode;
import com.swa99ylum.pjv.bean.ObjectJSONNode;
import com.swa99ylum.pjv.sample.FileUtils;
import com.swa99ylum.pjv.validator.DateFormatValidator;
import com.swa99ylum.pjv.validator.ExclusionValidator;
import com.swa99ylum.pjv.validator.InclusionValidator;
import com.swa99ylum.pjv.validator.KeyGenerator;
import com.swa99ylum.pjv.validator.UniqueValidator;
import com.swa99ylum.pjv.validator.Validator;

public class Test1 {
	public static void main(String[] args) throws Exception {
		String filePath = Test1.class.getResource("json_0400.txt").getPath();
		
		//step1、获取 json
		String json = null;
		try {
			json = FileUtils.getFileContent(filePath);
		} catch (Exception e) {
			System.err.println("从 文件中，读取 json 有误");
		}
		
//		System.out.println(json);
		
		//step2、定义 json 的 nodeFrame
		@SuppressWarnings("serial")
		Map<String, Object[]> nodeFrame = new HashMap<String, Object[]>(){{
			put("$[O]", new Object[]{
					new ObjectJSONNode("data")});
			
			
			put("$[O].data[O]", new Object[]{
					new ArrayJSONNode("request")});
			
			Validator v1 = new ExclusionValidator(new String[]{""});
			Validator v2 = new DateFormatValidator("YYYY/MM/DD");
			Validator v3 = new InclusionValidator(new String[]{"C", "I"});
			Validator v4 = new UniqueValidator(new KeyGenerator() {

				@Override
				public String generate(Object rootObject, String[] nodePath, String nodeName, Map<String, Object> parentValue, Object value) {
					
					Object v1 = parentValue.get("MASTER_ORDER_NO");
					Object v2 = value;
					
					return v1 + "-" + v2;
				}
			});
			
			put("$[O].data[O].request[A]", new Object[]{
					new JSONNode("MASTER_ORDER_NO", v1), 
					new JSONNode("SUB_ORDER_NO", v1, v4), 
					"DEALER_NO", 
					new JSONNode("ORDER_DATE", v1, v2),
					"ORDER_TYPE",
					
					"CAR_LIMIT_STATE",
					"CAR_LIMIT_REASON",
					"PACKAGE_CODE",
					new JSONNode("CAR_MODEL", v1),
					new JSONNode("INDICATOR", v3),
					new ArrayJSONNode("OPTION")});
			
			put("$[O].data[O].request[A].OPTION[A]", new Object[]{
					new JSONNode("MASTER_ORDER_NO", v1), 
					new JSONNode("SUB_ORDER_NO", v1), 
					new JSONNode("FAMILY_CODE", v1),
					new JSONNode("ATWRT", v1)});
			
		}};
		
		//step3、定义 errorMap，用于存储 验证出来的 错误结果
		Map<String, String> errorMap = new LinkedHashMap<String, String>();
		
		//step4、验证 json
		PluggableJSONValidator p = new PluggableJSONValidator(json, nodeFrame, Fuse.OBJECT, errorMap);
		p.parse();
		
		for(Entry<String, String> entry : errorMap.entrySet()) {
			System.out.println(entry.getKey() + " => " + entry.getValue());
		}
		
	}
}
